import TcpClient from '../until/Tcp';
import {logger} from '../until/log';
import config from '../../config';
import { Context } from 'koa';

/**
 * 设备统计控制器
 * 提供设备在线状态和掉线统计的API接口
 */
class DeviceStatsController {
    private tcpClient: TcpClient;

    constructor() {
        this.tcpClient = TcpClient.getInstance();
    }

    /**
     * 获取所有设备统计信息
     * GET /api/device-stats
     */
    public getDeviceStatistics = (ctx: Context): void => {
        const { gatewayIp } = ctx.query; // 从查询参数中获取 gatewayIp
        try {
            const statistics = this.tcpClient.getDeviceStatistics(gatewayIp as string);
            
            ctx.body = {
                success: true,
                code: 200,
                data: statistics,
                timestamp: Date.now()
            };
        } catch (error) {
            logger.error('获取设备统计信息失败:', error);
            ctx.status = 500;
            ctx.body = {
                code: 500,
                success: false,
                message: '获取设备统计信息失败',
                error: error instanceof Error ? error.message : '未知错误'
            };
        }
    };

    /**
     * 获取指定设备状态
     * GET /api/device-stats/:deviceId
     */
    public getDeviceStatus = (ctx: Context): void => {
        const { deviceId } = ctx.params;
        const { gatewayIp } = ctx.query; // 从查询参数中获取 gatewayIp
        
        if (!deviceId) {
            ctx.status = 400;
            ctx.body = {
                success: false,
                message: '设备ID不能为空'
            };
            return;
        }

        try {
            const deviceStatus = this.tcpClient.getDeviceStatus(deviceId, gatewayIp as string);
            
            if (!deviceStatus) {
                ctx.status = 404;
                ctx.body = {
                    success: false,
                    message: `设备 ${deviceId} 未找到`
                };
                return;
            }

            ctx.body = {
                success: true,
                data: deviceStatus,
                timestamp: Date.now()
            };
        } catch (error) {
            logger.error('获取设备状态失败:', error);
            ctx.status = 500;
            ctx.body = {
                success: false,
                message: '获取设备状态失败',
                error: error instanceof Error ? error.message : '未知错误'
            };
        }
    };

    /**
     * 重置设备掉线计数
     * POST /api/device-stats/:deviceId/reset-offline-count
     */
    public resetDeviceOfflineCount = (ctx: Context): void => {
        const { deviceId } = ctx.params;
        const { gatewayIp } = ctx.request.body; // 从请求体中获取 gatewayIp
        
        if (!deviceId) {
            ctx.status = 400;
            ctx.body = {
                success: false,
                message: '设备ID不能为空'
            };
            return;
        }

        try {
            const success = this.tcpClient.resetDeviceOfflineCount(deviceId, gatewayIp as string);
            
            if (!success) {
                ctx.status = 404;
                ctx.body = {
                    success: false,
                    message: `设备 ${deviceId} 未找到`
                };
                return;
            }

            ctx.body = {
                success: true,
                message: `设备 ${deviceId} 掉线计数已重置`,
                timestamp: Date.now()
            };
        } catch (error) {
            logger.error('重置设备掉线计数失败:', error);
            ctx.status = 500;
            ctx.body = {
                success: false,
                message: '重置设备掉线计数失败',
                error: error instanceof Error ? error.message : '未知错误'
            };
        }
    };

    /**
     * 获取在线设备列表
     * GET /api/device-stats/online
     */
    public getOnlineDevices = (ctx: Context): void => {
        const { gatewayIp } = ctx.query;
        try {
            const statistics = this.tcpClient.getDeviceStatistics(gatewayIp as string);
            const onlineDevices = statistics.deviceDetails.filter(device => device.isOnline);
            
            ctx.body = {
                success: true,
                data: {
                    count: onlineDevices.length,
                    devices: onlineDevices
                },
                timestamp: Date.now()
            };
        } catch (error) {
            logger.error('获取在线设备列表失败:', error);
            ctx.status = 500;
            ctx.body = {
                success: false,
                message: '获取在线设备列表失败',
                error: error instanceof Error ? error.message : '未知错误'
            };
        }
    };

    /**
     * 获取离线设备列表
     * GET /api/device-stats/offline
     */
    public getOfflineDevices = (ctx: Context): void => {
        const { gatewayIp } = ctx.query;
        try {
            const statistics = this.tcpClient.getDeviceStatistics(gatewayIp as string);
            const offlineDevices = statistics.deviceDetails.filter(device => !device.isOnline);
            
            ctx.body = {
                success: true,
                data: {
                    count: offlineDevices.length,
                    devices: offlineDevices
                },
                timestamp: Date.now()
            };
        } catch (error) {
            logger.error('获取离线设备列表失败:', error);
            ctx.status = 500;
            ctx.body = {
                success: false,
                message: '获取离线设备列表失败',
                error: error instanceof Error ? error.message : '未知错误'
            };
        }
    };

    /**
     * 获取设备掉线排行榜
     * GET /api/device-stats/offline-ranking
     */
    public getDeviceOfflineRanking = (ctx: Context): void => {
        const { limit = '10', gatewayIp } = ctx.query;
        try {
            const limitNum = parseInt(limit as string, 10);

            if (isNaN(limitNum) || limitNum <= 0) {
                ctx.status = 400;
                ctx.body = {
                    success: false,
                    message: 'limit 参数必须是大于0的数字'
                };
                return;
            }

            const statistics = this.tcpClient.getDeviceStatistics(gatewayIp as string);
            const offlineRanking = statistics.deviceDetails
                .filter(device => !device.isOnline)
                .sort((a, b) => b.offlineCount - a.offlineCount)
                .slice(0, limitNum);

            ctx.body = {
                success: true,
                data: {
                    count: offlineRanking.length,
                    devices: offlineRanking
                },
                timestamp: Date.now()
            };
        } catch (error) {
            logger.error('获取设备掉线排行榜失败:', error);
            ctx.status = 500;
            ctx.body = {
                success: false,
                message: '获取设备掉线排行榜失败',
                error: error instanceof Error ? error.message : '未知错误'
            };
        }
    };
}

export default DeviceStatsController;